package com.ytjj.qmyx.mall.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.dto.mqdto.AppDataStatisticsActivationDto;
import com.ytjj.common.dto.mqdto.AppDataStatisticsExposureDto;
import com.ytjj.common.dto.mqdto.AppDataStatisticsUsersActiveDto;
import com.ytjj.common.dto.mqdto.AppDataStatisticsUsersBehaviorDto;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.utils.IPUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.enums.UserBehaviorActivityTypeEnums;
import com.ytjj.qmyx.mall.model.AdvertReport;
import com.ytjj.qmyx.mall.model.UserRegisterRequestDto;
import com.ytjj.qmyx.mall.model.request.AppDataStatisticsActivationRequest;
import com.ytjj.qmyx.mall.model.request.AppDataStatisticsDynamicExposureRequest;
import com.ytjj.qmyx.mall.model.request.AppDataStatisticsUsersActiveRequest;
import com.ytjj.qmyx.mall.model.request.AppDataStatisticsUsersBehaviorRequest;
import com.ytjj.qmyx.mall.service.AdvertReportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * app数据统计接口
 */
@RestController
@RequestMapping("/app/data")
@Slf4j
@RefreshScope
public class AppDataStatisticsController extends BaseController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private AdvertReportService advertReportService;
    @Value("${amqp.push.flag:1}")
    private String amqp_delay_flag;//消息延迟发送开关 1-开启 0-关闭
    Executor pools = new ThreadPoolExecutor(5, 10, 5,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024 * 1024));


    /**
     * app激活
     * @return
     */
    @PostMapping("/activation")
    public CommonResult activation(@RequestBody AppDataStatisticsActivationRequest activation) {
        String uuid = TokenUtil.getRequest().getHeader("uuid");
        String imei = TokenUtil.getImei();
        String oaid = TokenUtil.getOaid();
        String osVersion = String.valueOf(TokenUtil.getOsVersion());
        String source = TokenUtil.getSource();//ios/android
        String channel=TokenUtil.getChannel();
        String ip = IPUtil.getIpAddress(TokenUtil.getRequest());
        AppDataStatisticsActivationDto dto = new AppDataStatisticsActivationDto();
        BeanUtils.copyProperties(activation, dto);
        dto.setUuid(uuid);
        dto.setIp(ip);
        dto.setCreateTime(new Date());
        dto.setPlatform(source);
        dto.setImei(imei);
        dto.setOaid(oaid);
        dto.setOsVersion(osVersion);
        try {
            pools.execute(() -> {
                rabbitTemplate.convertAndSend(QueueConstants.APP_ACTIVATION, JSONObject.toJSONString(dto, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
            });
        } catch (Exception e) {
            log.error("===guobao send mq is error:{}", e);
        }

        //头条、快手、抖音推广数据回传(激活数据)
        if (channel.contains("ytjj-ks") || channel.contains("ytjj-tt") || channel.contains("ytjj-dy")) {
            AdvertReport advertReport=new AdvertReport();
            advertReport.setChannel(channel);
            advertReport.setImei(imei);
            advertReport.setOaid(oaid);
            advertReport.setIp(ip);
            advertReport.setToken(TokenUtil.getToken());
            advertReport.setType("APP_ACTIVE");
            advertReport.setPlatform(TokenUtil.getSource());
            advertReportService.saveAdvertReport(advertReport);
        }
        return CommonResult.success();
    }

    /**
     * 用户活跃
     * @param usersActive
     * @return
     */
    @PostMapping("/userActive")
    public CommonResult userActive(@RequestBody AppDataStatisticsUsersActiveRequest usersActive) {
        String uuid = TokenUtil.getRequest().getHeader("uuid");
        String imei = TokenUtil.getImei();
        String oaid = TokenUtil.getOaid();
        String osVersion = String.valueOf(TokenUtil.getOsVersion());
        String ip = IPUtil.getIpAddress(TokenUtil.getRequest());
        String channel = TokenUtil.getChannel();
        String source = TokenUtil.getSource();//ios/android
        AppDataStatisticsUsersActiveDto dto = new AppDataStatisticsUsersActiveDto();
        dto.setUuid(uuid);
        dto.setIp(ip);
        try {
            UsersResponse usersResponse = getCurrentUser();
            dto.setUserId(usersResponse.getId().toString());
        } catch (Exception e) {
            log.error("===未登录===");
        }
        dto.setCreateTime(new Date());
        dto.setChannel(channel);
        dto.setPlatform(source);
        dto.setImei(imei);
        dto.setOaid(oaid);
        dto.setOsVersion(osVersion);
        try {
            pools.execute(() -> {
                rabbitTemplate.convertAndSend(QueueConstants.APP_USERACTIVE, JSONObject.toJSONString(dto, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
            });
        } catch (Exception e) {
            log.error("=== guobao userActive send mq is error:{}", e);
        }
        return CommonResult.success();
    }

    /**
     * 用户行为
     * @param usersBehavior
     * @return
     */
    @PostMapping("/userBehavior")
    public CommonResult userBehavior(@RequestBody AppDataStatisticsUsersBehaviorRequest usersBehavior) {
        String uuid = TokenUtil.getRequest().getHeader("uuid");
        String ip = IPUtil.getIpAddress(TokenUtil.getRequest());
        String channel = TokenUtil.getChannel();
        String source = TokenUtil.getSource();//ios/android

        AppDataStatisticsUsersBehaviorDto dto = new AppDataStatisticsUsersBehaviorDto();
        BeanUtils.copyProperties(usersBehavior, dto);
        dto.setDuration(usersBehavior.getItem().getDuration());
        dto.setId(usersBehavior.getItem().getId());
        dto.setEventName(usersBehavior.getItem().getEventName());
        dto.setSourcePage(usersBehavior.getItem().getSourcePage());
        dto.setPlayCompleted(String.valueOf(usersBehavior.getItem().isPlayCompleted()));
        dto.setUuid(uuid);
        dto.setIp(ip);
        try {
            UsersResponse usersResponse = getCurrentUser();
            dto.setUserId(usersResponse.getId().toString());
        } catch (Exception e) {
            log.error("===未登录===");
        }
        dto.setCreateTime(new Date());
        dto.setChannel(channel);
        dto.setPlatform(source);
        dto.setActivityType(null == UserBehaviorActivityTypeEnums.getActivityType(usersBehavior.getModule())
                ? UserBehaviorActivityTypeEnums.COMMON.name()
                : UserBehaviorActivityTypeEnums.getActivityType(usersBehavior.getModule()));

        dto.setAuthorId(usersBehavior.getItem().getUserId());
        dto.setDynamicType(usersBehavior.getItem().getType());
        try {
            if (amqp_delay_flag.equals("1")) {//如果延迟开启
                Random random = new Random();
                int randomTime = random.nextInt(20);
                MessagePostProcessor messagePostProcessor = message -> {
                    // 延时randomTime秒
                    message.getMessageProperties().setHeader("x-delay", randomTime * 1000);
                    return message;
                };
                rabbitTemplate.convertAndSend(QueueConstants.APP_USERBEHAVIOR, dto, messagePostProcessor);
            }else {
                pools.execute(() -> {
                    rabbitTemplate.convertAndSend(QueueConstants.APP_USERBEHAVIOR, dto);
                });
            }
        } catch (Exception e) {
            log.error("===guobao userBehavior send mq is error: {}", e);
        }

        return CommonResult.success();
    }

    /**
     * 用户注册
     * @param requestDto
     * @return
     */
    @PostMapping("/userRegister")
    public CommonResult userRegister(@RequestBody UserRegisterRequestDto requestDto) {
        String channel = requestDto.getChannel();
        try {
            pools.execute(() -> {
                rabbitTemplate.convertAndSend(QueueConstants.APP_USERREGISTER, JSONObject.toJSONString(requestDto, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
            });
        } catch (Exception e) {
            log.error("guobao userRegister send mq is error:{}", e);
        }
        //头条、快手、抖音推广数据回传(注册数据)
        if (channel.contains("ytjj-ks") || channel.contains("ytjj-tt") || channel.contains("ytjj-dy")) {
            AdvertReport advertReport=new AdvertReport();
            advertReport.setChannel(channel);
            advertReport.setImei(requestDto.getImei());
            advertReport.setOaid(requestDto.getOaid());
            advertReport.setIp(requestDto.getIp());
            advertReport.setToken(requestDto.getToken());
            advertReport.setType("APP_REGISTER");
            advertReport.setPlatform(requestDto.getPlatform());
            advertReportService.saveAdvertReport(advertReport);
        }
        return CommonResult.success();
    }

    /**
     * 动态曝光埋点
     * @return
     */
    @PostMapping("/dynamicExposure")
    public CommonResult dynamicExposure(@RequestBody AppDataStatisticsDynamicExposureRequest request) {
        String uuid = TokenUtil.getRequest().getHeader("uuid");
        String ip = IPUtil.getIpAddress(TokenUtil.getRequest());
        String channel = TokenUtil.getChannel();
        String source = TokenUtil.getSource();//ios/android

        AppDataStatisticsExposureDto dto = new AppDataStatisticsExposureDto();
        dto.setUuid(uuid);
        dto.setNetworkType(request.getNetworkType());
        dto.setIp(ip);
        dto.setCreateTime(new Date());
        dto.setChannel(channel);
        dto.setPlatform(source);
        dto.setDynamicIds(request.getDynamicIds());
        try {
            pools.execute(() -> {
//                rabbitTemplate.convertAndSend(QueueConstants.APP_DYNAMIC_EXPOSURE, JSONObject.toJSONString(dto, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
            });
        } catch (Exception e) {
            log.error("===guobao dynamicExposure send mq is error:{}", e);
        }
        return CommonResult.success();
    }
}
